package cn.site.modules.sys.web;

import cn.site.core.config.Global;
import cn.site.core.utils.CacheUtils;
import cn.site.core.utils.CookieUtils;
import cn.site.core.utils.StringUtils;
import cn.site.core.web.BaseController;
import cn.site.modules.sys.entity.User;
import cn.site.modules.sys.utils.UserUtils;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}")
public class LoginController extends BaseController {

    /**
     * 登录成功，进入管理首页
     * @param request
     * @param response
     * @return
     */
    @RequiresUser
    @RequestMapping(value = "")
    public String index(HttpServletRequest request, HttpServletResponse response) {
        User user = UserUtils.getUser();
        // 未登录，则跳转到登录页
        if(user.getId() == null){
            return "redirect:" + Global.getAdminPath() + "/login";
        }

//        Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
//        if ((principal != null) && (principal.getRoleId() != 0)) {
//            return "redirect:" + Global.getAdminPath() + "/sysIndex";
//        }

        // 登录成功后，验证码计算器清零
        isValidateCodeLogin(user.getLoginName(), false, true);

        // 登录成功后，获取上次登录的当前站点ID
        //UserUtils.putCache("siteId", CookieUtils.getCookie(request, "siteId"));

        return "modules/sys/sysIndex";
    }

    /*登录页面*/
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        User user = UserUtils.getUser();
        // 如果已经登录，则跳转到管理首页
        if(user.getId() != null){
            return "redirect:" + Global.getAdminPath();
        }

        return "modules/sys/sysLogin";
    }

    /**
     * 真正登录的POST请求由Filter完成
     * (登陆失败会触发该请求)
     * @param username
     * @param model
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String username, Model model) {
        User user = UserUtils.getUser();
        // 如果已经登录，则跳转到管理首页
        if(user.getId() != null){
            return "redirect:" + Global.getAdminPath();
        }

        model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
        //登录失败3次会输入验证码
        model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(username, true, false));

        return "modules/sys/sysLogin";
    }

    /**
     * 是否是验证码登录
     * @param useruame 用户名
     * @param isFail 计数加1
     * @param clean 计数清零
     * @return
     */
    public static boolean isValidateCodeLogin(String useruame, boolean isFail, boolean clean){
        Map<String, Integer> loginFailMap = (Map<String, Integer>) CacheUtils.get("loginFailMap");
        if (loginFailMap == null){
            loginFailMap = Maps.newHashMap();
            CacheUtils.put("loginFailMap", loginFailMap);
        }
        Integer loginFailNum = loginFailMap.get(useruame);
        if (loginFailNum == null){
            loginFailNum = 0;
        }
        if (isFail){
            loginFailNum++;
            loginFailMap.put(useruame, loginFailNum);
        }
        if (clean){
            loginFailMap.remove(useruame);
        }
        return loginFailNum >= 3;
    }

    /**
     * 获取主题方案
     */
    @RequestMapping(value = "/theme/{theme}")
    public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request, HttpServletResponse response){
        if (StringUtils.isNotBlank(theme)){
            CookieUtils.setCookie(response, "theme", theme);
        }else{
            theme = CookieUtils.getCookie(request, "theme");
        }
        //回到要进行访问的页面
        return "redirect:"+request.getParameter("url");
    }

    /**
     * 文件下载
     * @param filePath
     * @param response
     * @return
     */
    @RequestMapping("/download")
    public String download(String filePath, HttpServletResponse response) {
        File file = new File(filePath);
        InputStream inputStream;
        try {
            inputStream = new FileInputStream(filePath);
            response.reset();
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            byte data[] = new byte[1024];
            while (inputStream.read(data, 0, 1024) >= 0) {
                outputStream.write(data);
            }
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
